<template>
<!--  <h2>项目列表</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工程代号" prop="projectCode">
        <el-input v-model="queryParams.projectCode" placeholder="请输入工程代号" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="projectId"/>
      <el-table-column label="项目名称" prop="projectName" align="center" />
      <el-table-column label="工程代号" prop="projectCode" align="center" />
      <el-table-column label="项目总体" prop="projectOverallName" align="center" />
      <el-table-column label="项目分类" prop="projectClassification" align="center" />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加/修改文件 -->
    <el-dialog :title="itemTitle" :visible.sync="itemOpen" width="35%" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="itemForm.projectName" placeholder="请输入项目名称" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工程代号" prop="projectCode">
              <el-input v-model="itemForm.projectCode" placeholder="请输入工程代号" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目总体" prop="projectOverall">
              <treeselect v-model="itemForm.projectOverall" :options="deptUserOptions" :show-count="true"
                          placeholder="请选择" :disable-branch-nodes="true" @select="onChangeTap" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目分类" prop="projectClassification">
              <el-select v-model="itemForm.projectClassification" placeholder="请输入项目分类" style="width: 100%;">
                <el-option v-for="dict in dict.type.XMFL" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="生产院" prop="deptIds">
              <el-select v-model="itemForm.deptIds" placeholder="请输入生产院" multiple  style="width: 100%;">
                <el-option v-for="dept in dept" :key="dept.deptName" :label="dept.deptName" :value="dept.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitItemForm">保 存</el-button>
        <el-button  @click="itemCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addItem, deleteItem, getItemDetail, getTableList, updateItem,findDept,deptTreeSelect} from "@/api/stage/stageManagement/itemList";
import {deptUserTree} from "@/api/archive/fileCollection/archiveApproval";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "index",
  components: { Treeselect },
  archive_Dicts: ['XMFL'],
  data() {
    const checkFieldCaption = (rule, value, callback) => {
      if (value) {
        var reg = /^[a-zA-Z]*$/; // 正则表达式，只匹配英文字符
        if (reg.test(value) === false) {
          callback(new Error('请输入英文'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      queryParams: {
        pageNum:1,
        pageSize:10,
        projectName: undefined,
        projectCode: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 遮挡层
      loading: true,
      // 表格数据
      tableDataList: [],
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      itemTitle: '',
      itemOpen: false,
      itemForm: {
        projectName: undefined,
        projectCode: undefined,
        projectOverall: undefined,
        projectClassification: undefined,
        deptIds: undefined
      },
      itemRules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectCode: [
          { required: true, message: "工程代号不能为空", trigger: "blur" },
          // { required: true, trigger: 'blur', validator: checkFieldCaption }
        ],
        projectOverall: [
          { required: true, message: "项目总体不能为空", trigger: "blur" }
        ],
        deptIds: [
          { required: true, message: "生产院不能为空", trigger: "blur" }
        ]
      },
      // 部门树选项
      deptOptions: [],
      // 人员树选项
      deptUserOptions: [],
      dept: [],
    }
  },
  created() {
    this.getDeptTreePost(); //归属部门树接口
    this.deptUserTreePost();//获取人员树接口
    this.getList()
    this.getDept();
  },
  methods: {
    // 生产院
    getDept(){
      findDept().then(r=>{
        this.dept = r.data;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.loading = true
      getTableList(this.queryParams).then(response=>{
        this.loading = false
        this.tableDataList = response.rows
        for (let i = 0; i < response.rows.length; i++) {
          this.tableDataList[i].itemOverall = this.getLabelById(response.rows[i].projectOverall)
        }
        this.total = response.total
      })
    },
    // 根据id获取对应的名称
    getLabelById(id) {
      function recurse(nodes) {
        for (let node of nodes) {
          if(node.id == id) {
            return node.label
          }
          if (node.children) {
            const label = recurse(node.children)
            if (label) return label
          }
        }
      }
      return recurse(this.deptUserOptions)
    },
    /** 查询部门下拉树结构 */
    getDeptTreePost() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /**获取人员树接口 */
    deptUserTreePost(){
      deptUserTree().then(response => {
        this.deptUserOptions = response.data;
        // 重命名树结构中的字段
        this.deptUserOptions.forEach(node => {
          this.appendUser(node);
        });
      })
    },
    appendUser(node) {
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.appendUser(child);
        });
      }
      if (node.userChildren && node.userChildren.length > 0) {
        node.children = [...(node.children || []), ...node.userChildren];
        delete node.userChildren;
      }
    },
    onChangeTap(node) {
      var flag = this.traverse(node, this.deptOptions[0])
      if(flag == true) {
        this.$nextTick(() => {
          this.form.submitUserId = null;
        })
        this.deptUserOptions = [...this.deptUserOptions];
      }
    },
    traverse(node, dept) {
      if(dept.id == node.id) {
        this.$message({ message: '选择的数据是部门节点,请选择人员节点', type: 'warning' })
        return true;
      }
      if(dept.children) {
        for(let child of dept.children) {
          if(this.traverse(node, child)) {
            return true;
          }
        }
      }
      return false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    // 增加项目
    handleAdd() {
      this.resetForm("itemForm");
      this.resetItemForm()
      this.itemTitle = '添加项目'
      this.itemOpen = true
    },
    resetItemForm() {
      this.itemForm = {
        projectName: undefined,
        projectCode: undefined,
        projectOverall: undefined,
        projectClassification: undefined
      }
    },
    // 修改
    handleUpdate(row) {
      this.resetForm("itemForm");
      this.resetItemForm()
      getItemDetail({projectId: row.projectId}).then(response=>{
        this.itemForm = response.data
        this.itemTitle = '修改项目'
        this.itemOpen = true
      })
    },
    // 保存
    submitItemForm() {
      this.$refs["itemForm"].validate(valid => {
        if(valid) {
          if(this.itemForm.projectId != undefined) {
            updateItem(this.itemForm).then(response=>{
              this.$modal.msgSuccess('修改成功')
              this.itemOpen = false
              this.getList()
            })
          } else {
            addItem(this.itemForm).then(response=>{
              this.$modal.msgSuccess('新增成功')
              this.itemOpen = false
              this.getList()
            })
          }
        }
      })
    },
    // 取消
    itemCancel() {
      this.itemOpen = false
    },
    // 删除
    handleDelete(row) {
      console.log(row)
      const projectId = row.projectId
      this.$modal.confirm('是否确认删除专业名称为"' + row.projectName + '"的数据项？').then(function() {
        return deleteItem({projectId: projectId})
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
}
</script>

<style scoped>

</style>
